package service

import (
	"demo/initialize"
	model "demo/models"
	"demo/models/response"
)

var DB = initialize.DB

type UserService struct{}

var user model.User
var users []model.User

// UserLogin 用户登录
func (u *UserService) UserLogin(username string, password string) (result response.Response) {
	DB.Where("user_name=? and password=?", username, password).First(&user)
	if &user != nil {
		result.Code = 200
		result.Data = user
		result.Msg = "登录成功"
		return result
	}
	result.Code = 200
	result.Data = nil
	result.Msg = "登录失败"
	return result

}

// GetUserById 根据据用户id查询用户详细信息
func (u *UserService) GetUserById(id string) (user model.User) {
	DB.Where("id=?", id).First(&user)
	return user
}

// GetAllUsers 获取所有用户信息
func (u *UserService) GetAllUsers() (users []model.User) {
	DB.Find(&users)
	return users
}

// GetAllUsersByPage 分页获取所有用户信息
func (u *UserService) GetAllUsersByPage(currentPage int, pageSize int) (page response.Page) {
	var total int64
	DB.Limit(pageSize).Offset((currentPage - 1) * pageSize).Find(&users)
	DB.Model(&model.User{}).Count(&total)
	page.CurrentPage = currentPage
	page.PageSize = pageSize
	page.TotalCount = int(total)
	page.TotalPage = int(total / int64(pageSize))
	page.Data = users
	return page
}

// CreateUser 创建用户
func (u *UserService) CreateUser(user model.User) interface{} {
	DB.Table("user").Create(&user)
	return user
}

// DeleteUserById  删除用户
func (u *UserService) DeleteUserById(id string) interface{} {
	tx := DB.Delete(&model.User{}, id)
	return tx
}

// UpdateUserById 更新用户
func (u *UserService) UpdateUserById(user model.User) interface{} {
	DB.Table("user").Updates(user)
	return user
}
